# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "人保寿险金色天使疾病保险"

    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(0, 16)],
            # 性别
            "gender": ["M", "F"],
            # 保障期限
            "expire": ["20年", "30岁"],
            # 交费间隔
            "interval": ["0", "3", "5"],
            # 保险金额
            "money": ["50000", "200000", "300000", "400000", "500000"]
        }
        for v in product(plan["year"], plan["gender"], plan["expire"], plan["interval"], plan["money"]):
            if v[3] == "0":
                payType = "一次交清"
            else:
                payType = "年交"
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4], payType
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4], payType
            ))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"header": {"transRefGUID": "1231234342356767878", "transDate": "2017-8-14", "transTime": "11:29:00",
                           "businessType": "001"}, "body": {"combCode": "C65383", "policyType": "1",
                                                            "inputFactors": {"age": dt["year"], "sex": dt["gender"],
                                                                             "payEndYear": "1Y" if dt["interval"] == "0" else dt["interval"] + "Y", "insuYear": "20Y" if dt["expire"] == "20年" else "30A",
                                                                             "amnt": dt["money"], "combcode": "C65383",
                                                                             "organid": "-1", "birth": "{0}-01-01".format(str(2020-int(dt["year"])))},
                                                            "addRisks": []}}
        print( data )
        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "success" in r.text:
            price = Helper.decimalParse(r.json()["data"]["mainPrem"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格数据失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
